import request from '@/config/request'
import { getAnswerScoreable, generateStudentAnswer, jywConvertToXkw } from '@/utils/question'
import { getSelfModuleSubjectApi, questionSplitApi } from '@/api/common'

// 获取课程列表
export const getStudentCoursesList = (data) => {
  return new Promise((resolve) => {
    Promise.all([
      request.get('/question-api/question/courses/getStudentCoursesList', data),
      getSelfModuleSubjectApi()
    ]).then((res) => {
      const [subjectIdListData, moduleSubjectListData] = res
      const { data: subjectIdList } = subjectIdListData
      const { data: moduleSubjectList } = moduleSubjectListData

      // 获取已经开通的科目
      if (Array.isArray(moduleSubjectList) && moduleSubjectList.length > 0) {
        const selfSubjectList = moduleSubjectList.filter((i) => i.moduleId === '4')
        if (Array.isArray(subjectIdList) && selfSubjectList.length > 0) {
          const copySubjectIdList = JSON.parse(JSON.stringify(subjectIdList))
          const selfSubjectIds = selfSubjectList.map((i) => i.subject)
          subjectIdList.splice(0, subjectIdList.length)
          subjectIdList.push(...copySubjectIdList.filter((i) => selfSubjectIds.includes(i.value)))
        } else {
          subjectIdList.splice(0, subjectIdList.length)
        }
      } else {
        subjectIdList.splice(0, subjectIdList.length)
      }

      resolve(subjectIdListData)
    })
  })
}

// 获取知识点列表
export const getKpointList = (data) => {
  return request.post('/app-api/exam/userKpointData/getKpointData', data)
}

// 获取知识点树
export const getUserKpointTreeApi = (data) => {
  return request.get('/app-api/exam/userKpointData/getKnowledgePointTree', data)
}

// 获取练习记录（学科网）
export const getKpointPractice = (data) => {
  return request.post('/app-api/exam/kpointPractice/goPractice', data)
}

// 获取练习记录（英语听说）
export const getEnglishPracticeApi = (data) => {
  return request.post('/app-api/exam/kpointPractice/goPracticeHearAbout', data)
}

// 通过id获取练习题目
export const getStudentQuestionById = (data) => {
  return request.get('/app-api/exam/praccticeStudentQuestion/getQuestion', data)
}

// 获取下一道练习题目（学科网）
export const getNextQuestion = (data) => {
  return new Promise(async (resovle) => {
    const res = await request.post('/app-api/exam/kpointPractice/nextProblem', data)

    try {
      if (res.data) {
        // 如果不是学科网题目，将题目改为学科网的题目结构
        const q = res.data
        // 菁优网
        if (q.sourceType && q.sourceType === '3') {
          q.typeName = q.typename
          jywConvertToXkw(q)

          // 题目解析
          const { data: questionSplitRes = [] } = await questionSplitApi([
            {
              questionId: q.questionId,
              stem: q.stem,
              answer: q.answer,
              explanation: q.explanation
            }
          ])

          q.question = {}
          q.question.stem = JSON.parse(
            questionSplitRes[0].stem.replace(
              /<fieldset style=\\\"margin-top:0.1rem;font-size:0.26rem\\\">\\n /,
              '<fieldset style=\\"margin-top:0.1rem;font-size:0.26rem\\">'
            )
          )
          q.question.answer = JSON.parse(questionSplitRes[0].answer)
          q.question.explanation = JSON.parse(questionSplitRes[0].explanation)
        }

        const {
          data: { typeId, typename }
        } = res

        if (!typename) {
          const { data } = await getQuestionType({ id: typeId })
          res.data.typeName = data && data.name ? data.name : '未知题型'
        } else {
          res.data.typeName = typename
        }

        res.data.answerScoreable = getAnswerScoreable({
          stem: res.data.question.stem,
          answer: res.data.question.answer
        })
      }
    } catch (error) {
      console.error(error)
    }

    resovle(res)
  })
}

// 获取下一道练习题目（英语听说）
export const getNextEnglishQuestionApi = (data) => {
  return new Promise(async (resovle) => {
    const { questionTypeId } = data
    const res = await request.post('/app-api/exam/kpointPractice/nextProblemHearAbout', data)

    /**
     * 生成听后选择题
     * @param {*} questions 题目列表
     * @returns
     */
    const genChooseQuestion = (questions = []) => {
      const stem = {
        structure_type: 'collector.choose',
        info: {
          question: questions
        }
      }

      let answerAnSqs = []
      questions.forEach((q) => {
        const { anSqs = [] } = JSON.parse(q.answer)

        answerAnSqs.push([...anSqs])
      })
      const answer = {
        anSqs: answerAnSqs
      }

      return {
        answer: JSON.stringify(answer),
        courseId: 10086,
        questionId: null,
        questionIds: questions.map((q) => q.questionId),
        kpointPracticeIds: questions.map((q) => q.kpointPracticeId),
        questionSort: null,
        sourceType: '10086',
        stem: JSON.stringify(stem),
        typeId: '1008601'
      }
    }

    if (res.data && questionTypeId === '1008601') {
      res.data = genChooseQuestion(res.data)
    } else if (res.data) {
      res.data = res.data[0]
    } else {
      // 没有更多题目了
    }

    try {
      if (res.data) {
        res.data.stem = JSON.parse(res.data.stem)
        res.data.answer = JSON.parse(res.data.answer)
        res.data['localStudentAnswer'] = {
          studentAnswer: generateStudentAnswer({
            init: res.data.answer
          }),
          studentAnswerUrl: '',
          studentDuration: 0
        }
        res.data['localStudentAnswerStatus'] = 0
      }
    } catch (error) {
      console.error(error)
    }

    resovle(res)
  })
}

// 确认答案
export const checkAnswer = (data) => {
  return request.post('/app-api/exam/praccticeStudentQuestion/checkAnswers', data)
}

// 更新答案
export const updateAnswerApi = (data) => {
  return request.post('/app-api/exam/praccticeStudentQuestion/updateAnswers', data)
}

// 确认答案（举一反三）
export const recommendCheckAnswer = (data) => {
  return request.post('/app-api/exam/recommend-pratice/checkAnswer', data)
}

// 确认答案（英语听说）
export const englishCheckAnswerApi = (data) => {
  return request.post('/app-api/exam/praccticeStudentQuestion/checkAnswersHearAbout', data)
}

// 结束练习
export const quitPracticeApi = (data) => {
  return request.get('/app-api/exam/kpointPractice/quitPractice', data)
}

// 获取题型
export const getQuestionType = (data) => {
  return request.get('/app-api/question/App/type/get', data)
}

// 获取题型（英语听说）
export const getEnglishQuestionTypeListApi = (data) => {
  return request.post('/app-api/exam/userKpointData/getQuestionTypeList', data)
}

// 上传学生答案批改
export const hearAboutScoreApi = (data) => {
  return request.post('/app-api/exam/praccticeStudentQuestion/hearAboutScore', data)
}

// 获取菁优网题目详情
export const getListCompleteByIdsApi = (data) => {
  return request.get('/question-api/question/question/getListCompleteByIds', data)
}
